<template>
  <div class="client-profile-page">
    <el-card class="profile-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>

      <!-- 未登录时显示提示 -->
      <div v-if="!isAuthenticated" class="error-message">
        <el-alert
          title="未登录或登录已过期"
          type="warning"
          description="请重新登录后访问此页面"
          show-icon
          :closable="false"
        />
        <el-button type="primary" class="login-button" @click="handleRelogin">
          返回登录
        </el-button>
      </div>

      <!-- 已登录时显示表单 (无论加载是否成功，加载失败只通过 ElMessage 提示) -->
      <!-- 表单的数据绑定profileForm 会反映加载结果 -->
      <el-form
        v-else
        ref="profileFormRef"
        :model="profileForm"
        :rules="rules"
        label-width="100px"
        class="profile-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="所属公司" prop="company">
          <el-input v-model="profileForm.company" placeholder="请输入所属公司" />
        </el-form-item>

        <el-form-item label="修改密码" prop="newPassword">
          <el-input
            v-model="profileForm.newPassword"
            type="password"
            placeholder="如需修改密码请输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="profileForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存修改
          </el-button>
           <!-- 在已认证且加载失败时显示重试按钮 -->
           <el-button v-if="loadError" type="info" @click="loadUserProfile">
              重试加载资料
           </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUserById, updateUser } from '@/apis/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const profileFormRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const loadError = ref(null)

const isAuthenticated = computed(() => {
  return userStore.isAuthenticated && userStore.user
})

const currentUserId = computed(() => isAuthenticated.value ? userStore.user.id : null)

const profileForm = ref({
  id: null,
  username: '',
  realName: '',
  phone: '',
  company: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    if (profileForm.value.newPassword) {
       callback(new Error('请再次输入新密码'))
    } else {
       callback()
    }
  } else if (value !== profileForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入所属公司', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass, trigger: 'blur' }
  ]
}

const loadUserProfile = async () => {
  const userId = currentUserId.value

  if (!isAuthenticated.value || !userId) {
     console.warn('loadUserProfile skipped: User not authenticated or ID not available.');
     loading.value = false;
     profileForm.value = {};
     return;
  }

  loading.value = true;
  loadError.value = null;

  try {
    const response = await getUserById(userId);
    console.log('getUserById response:', response);

    if (response.code === 200 && response.data) {
      const userData = response.data;
      if (String(userData.userId) === String(userId)) {
         profileForm.value = {
            id: userData.userId,
            username: userData.username || '',
            realName: userData.realName || '',
            phone: userData.phone || '',
            company: userData.company || '',
            newPassword: '',
            confirmPassword: ''
         };
         loadError.value = null;
         console.log('User data loaded and ID matched. loadError is null.');
      } else {
         console.warn('User ID mismatch in loaded data:', userData.userId, 'expected:', userId);
         loadError.value = '加载的用户数据与当前用户不匹配';
         ElMessage.error(loadError.value);
         profileForm.value = {};
      }
    } else {
      loadError.value = response.msg || '获取用户信息失败';
      ElMessage.error(loadError.value);
      profileForm.value = {};
    }
  } catch (error) {
    console.error('获取用户信息出错:', error);
    loadError.value = '获取用户信息时发生错误，请稍后重试';
    ElMessage.error(loadError.value);
    profileForm.value = {};
  } finally {
    loading.value = false;
  }
}

const handleSubmit = async () => {
  if (!profileFormRef.value || !isAuthenticated.value) return;

  submitting.value = true;

  try {
    const valid = await profileFormRef.value.validate();

    if (valid) {
      const updateData = {
        realName: profileForm.value.realName,
        phone: profileForm.value.phone,
        company: profileForm.value.company,
      }

      if (profileForm.value.newPassword) {
        updateData.password = profileForm.value.newPassword;
      }

      const userId = currentUserId.value;
      if (!userId) {
          ElMessage.error('无法获取当前用户ID，无法保存');
          submitting.value = false;
          return;
      }

      const response = await updateUser(userId, updateData);

      console.log('updateUser response:', response);

      if (response.code === 200) {
        ElMessage.success(response.msg || '更新成功');
        profileForm.value.newPassword = '';
        profileForm.value.confirmPassword = '';
      } else {
        ElMessage.error(response.msg || '更新失败');
      }
    } else {
       ElMessage.warning('请检查填写的信息是否正确');
    }
  } catch (error) {
    console.error('更新用户信息出错:', error);
    ElMessage.error('更新失败');
  } finally {
    submitting.value = false;
  }
}

const handleRelogin = () => {
  userStore.logout()
  router.push('/login')
}

watch(currentUserId, (newUserId, oldUserId) => {
    console.log('currentUserId changed:', oldUserId, '->', newUserId);
    if (newUserId) {
        loadUserProfile();
    } else {
        profileForm.value = {};
        loadError.value = null;
        loading.value = false;
        console.log('No current user ID, clearing profile data.');
    }
}, { immediate: true });
</script>

<style scoped>
.client-profile-page {
  padding: 2rem;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  margin-top: 1rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-form {
  max-width: 500px;
  margin: 0 auto;
}

.error-message {
  text-align: center;
  padding: 2rem;
}

.login-button, .retry-button {
  margin-top: 1rem;
}
</style> 